package com.lippeng.taohua.db.util;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.lippeng.taohua.db.domain.SuperDomain;
import com.lippeng.taohua.db.exception.TaoHuaDBException;

/**
 * Deal with the ResultSet and return the Need type
 * 
 * @author lippeng
 * 
 */
public class ResultBacker {

	private SuperDomain domain;
	private Class<? extends SuperDomain> classs;
	private Field[] fields;

	/**
	 * Constructor
	 */
	public ResultBacker(SuperDomain domain) {
		this.domain = domain;
		this.classs = domain.getClass();
		init();
	}

	/**
	 * Methods
	 */

	private void init() {
		this.fields = classs.getDeclaredFields();
	}

	/**
	 * 
	 * @param resultSet
	 * @return
	 */
	public Long count(ResultSet resultSet) {
		Long value = null;
		try {
			if (resultSet.first()) {
				value = resultSet.getLong(0);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new TaoHuaDBException("Count ResultSet has not first row");
		}
		return value;
	}

	public List<SuperDomain> select(ResultSet resultSet) {
		List<SuperDomain> valueList = new ArrayList<SuperDomain>();
		try {
			while (resultSet.next()) {
				SuperDomain domain = classs.newInstance();
				for (int i = 0; i < fields.length; i++) {
					fields[i].set(domain, resultSet.getObject(i));
				}
				valueList.add(domain);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new TaoHuaDBException("ResultSet to Object Exception 1");
		} catch (InstantiationException e) {
			e.printStackTrace();
			throw new TaoHuaDBException("ResultSet to Object Exception 2");
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			throw new TaoHuaDBException("ResultSet to Object Exception 3");
		}
		return valueList;
	}

	public SuperDomain load(ResultSet resultSet) {
		try {
			while (resultSet.first()) {
				for (int i = 0; i < fields.length; i++) {
					fields[i].set(domain, resultSet.getObject(i));
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new TaoHuaDBException("ResultSet to Object Exception 1");
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			throw new TaoHuaDBException("ResultSet to Object Exception 3");
		}
		return domain;
	}

}
